package com.kye.express.business.name_certification;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.databinding.ActivityNameCertificationBinding;
import com.kye.express.utils.StringFormatUtils;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class NameCertificationActivity extends BaseAppCompatActivity implements NameCertificationContract.NameCertificationView {

    private ActivityNameCertificationBinding mBinding;
    private String[] mIdTypeArray;
    private NameCertificationContract.NameCertificationPresenter mPresenter;
    private Dialog mDialog;

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, NameCertificationActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_name_certification);

        initEvent();
        initData();
    }

    private void initEvent() {
        setSupportActionBar(mBinding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        ToolbarManager.setToolbar(this, mBinding.toolbar);

        RxView.clicks(mBinding.linearLayoutIdType)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        new MaterialDialog.Builder(NameCertificationActivity.this)
                                .items(mIdTypeArray)
                                .itemsCallback(new MaterialDialog.ListCallback() {
                                    @Override
                                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                        mBinding.setIdType(text.toString());
                                    }
                                })
                                .show();
                    }
                });

        Observable.combineLatest(RxTextView.textChanges(mBinding.editTextId), RxTextView.textChanges(mBinding.editTextName), new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence charSequence, CharSequence charSequence2) throws Exception {
                return !TextUtils.isEmpty(charSequence) && charSequence2.length() >= 2;
            }
        })
                .observeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.setSubmitEnabled(aBoolean);
                    }
                });

        RxView.clicks(mBinding.buttonSubmit)
                .observeOn(Schedulers.computation())
                .compose(new DebounceObservableTransformer<>())
                .map(new Function<Object, Object>() {
                    @Override
                    public Object apply(Object o) throws Exception {
                        String name = mBinding.editTextName.getText().toString().trim();

                        if (StringFormatUtils.checkNameIsChinese(name)) {
                            return new IllegalArgumentException(getString(R.string.error_name_just_is_chinese));
                        }

                        String id = mBinding.editTextId.getText().toString().trim();
                        if (!checkID(mBinding.getIdType(), id)) {
                            return new IllegalArgumentException(getString(R.string.error_id_illegal_argument));
                        }

                        return o;
                    }
                })
                .compose(this.bindToLifecycleDestroy())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof IllegalArgumentException) {
                            ToastManager.show(NameCertificationActivity.this, ((IllegalArgumentException) o).getMessage());
                            return;
                        }

                        mPresenter.nameCertification(mBinding.editTextName.getText().toString().trim(), mBinding.getIdType(), mBinding.editTextId.getText().toString().trim());
                    }
                });
    }

    @NonNull
    private boolean checkID(String idType, String id) {
        String matches = "^\\d{15}$|^\\d{17}[\\dxX]$";
        if (idType.equals(mIdTypeArray[0])) {
            //身份证
            return StringFormatUtils.checkIDNumber(id);
        } else {
            if (idType.equals(mIdTypeArray[1])) {
                //军官/士官证
                matches = "^\\d{8}$";
            } else if (idType.equals(mIdTypeArray[2])) {
                //护照
                matches = "^[0-9a-zA-Z]{5,17}$";
            } else if (idType.equals(mIdTypeArray[3])) {
                //港澳通行证
                matches = "^[HMhm](\\d{10}|\\d{8})$";
            } else if (idType.equals(mIdTypeArray[4])) {
                //台湾通行证
                matches = "^\\d{8}$|^\\d{10}$";
            }

            Pattern regex = Pattern.compile(matches);
            Matcher matcher = regex.matcher(id);
            return matcher.matches();
        }
    }

    private void initData() {
        mPresenter = new NameCertificationContract.NameCertificationPresenter();
        mPresenter.bind(this);

        mIdTypeArray = getResources().getStringArray(R.array.name_certification_id_type);
        mBinding.setIdType(mIdTypeArray[0]);
    }

    @Override
    public void onError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void onLoading() {
        mDialog = KyeProgressDialog.show(this, mDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mDialog);
    }

    @Override
    public void onCertified() {
        finish();
    }
}
